package uestc.lj.gulishop.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import uestc.lj.common.utils.HttpUtils;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.common.utils.R;
import uestc.lj.gulishop.member.dao.MemberDao;
import uestc.lj.gulishop.member.entity.MemberEntity;
import uestc.lj.gulishop.member.entity.MemberLevelEntity;
import uestc.lj.gulishop.member.exception.PhoneExistException;
import uestc.lj.gulishop.member.feign.OrderFeignService;
import uestc.lj.gulishop.member.service.MemberLevelService;
import uestc.lj.gulishop.member.service.MemberService;
import uestc.lj.gulishop.member.vo.MemberLoginVO;
import uestc.lj.gulishop.member.vo.MemberRegisterVO;
import uestc.lj.gulishop.member.vo.SocialUser;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private OrderFeignService orderFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegisterVO memberRegisterVO) {
        MemberEntity memberEntity = new MemberEntity();
        // 1.判断手机号的唯一性
        checkPhoneUnique(memberRegisterVO.getPhone());
        // 1.设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        // 2.设置基本信息
        memberEntity.setUsername(memberRegisterVO.getUserName());
        memberEntity.setMobile(memberRegisterVO.getPhone());
        memberEntity.setNickname(memberRegisterVO.getUserName());
        memberEntity.setGender(0);
        // 3.密码存储
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = bCryptPasswordEncoder.encode(memberRegisterVO.getPassword());
        memberEntity.setPassword(encodedPassword);
        // 4.todo 其他默认信息

        // 5.插入数据库
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVO vo) {
        // 1.获取用户输入
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        // 2.与数据库中的检验比对
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", loginacct);
        MemberEntity memberEntity = baseMapper.selectOne(wrapper);
        if (memberEntity == null) {
            // 登陆失败
            return null;
        } else {
            // 进行比对
            String dbPassword = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (encoder.matches(password, dbPassword)) {
                // 登录成功
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    /**
     * 第三方登录
     *
     * @param socialUser
     * @return
     * @throws Exception
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 判断当前用户是否已经是第一次登录
        String uid = socialUser.getUid();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 此用户已经注册
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(entity);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            // 未注册则自动注册
            MemberEntity member = new MemberEntity();

            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccess_token());
                map.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONObject.parseObject(json);

                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String location = jsonObject.getString("location");

                    member.setNickname(name);
                    member.setGender("m".equals(gender) ? 1 : 0);
                    member.setCity(location);
                }
            } catch (Exception e) {
                // 服务调用超时
                e.printStackTrace();
            }
            member.setSocialUid(socialUser.getUid());
            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());
            baseMapper.insert(member);
            return member;
        }
    }

    @Override
    public R memberOrder(Map<String, Object> map) {
        return orderFeignService.list(map);
    }

}